package support

import (
	"context"
	"freechat-im/common"
	"freechat-im/config"
	"freechat-im/model"
	"gitee.com/goddesszz/gocommon/myutil"
	"github.com/sirupsen/logrus"
	"os"
)

// StartSubscribe 启动订阅，连接Nats
func StartSubscribe(sender func(*model.ChatMessage), eventSender func(any, string)) {
	endpoint := os.Getenv("NATS_ENDPOINT")
	//连接Nats
	config.InitNats(endpoint)

	go func() {
		//订阅节点消息
		sub, err3 := config.GetNatsConn().SubscribeSync("chat.message." + common.NodeName)
		if err3 != nil {
			logrus.Fatal("Nats订阅消息出错。", err3)
		}
		defer sub.Unsubscribe()

		for {
			msg, err := sub.NextMsgWithContext(context.Background())
			if err != nil {
				logrus.Error("接收订阅消息出错，即将退出接收订阅... err=", err)
				break
			}

			//收到订阅的数据
			var message = myutil.Deserialize[model.ChatMessage](msg.Data)
			logrus.Debug("接收订阅消息 Received on [%s]: '%s'\n", msg.Subject, message)

			sender(&message)
		}
	}()

	go func() {
		//订阅节点消息
		sub, err3 := config.GetNatsConn().SubscribeSync("chat.eventmsg." + common.NodeName)
		if err3 != nil {
			logrus.Fatal("Nats订阅消息出错。", err3)
		}
		defer sub.Unsubscribe()

		for {
			msg, err := sub.NextMsgWithContext(context.Background())
			if err != nil {
				logrus.Error("接收订阅消息出错，即将退出接收订阅... err=", err)
				break
			}

			//收到订阅的数据
			var eventMsg = myutil.Deserialize[model.MsgEvent](msg.Data)
			logrus.Debug("接收订阅消息 Received on [%s]: '%s'\n", msg.Subject, eventMsg)

			eventSender(eventMsg, eventMsg.SendTo)
		}
	}()
}
